package com.zzx.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzx.boot.common.BaseContext;
import com.zzx.boot.common.CustomException;
import com.zzx.boot.dto.OrdersDto;
import com.zzx.boot.mapper.OrderMapper;
import com.zzx.boot.pojo.*;
import com.zzx.boot.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Resource
    private OrderMapper mapper;
    @Autowired  //购物车
    private ShoppingCartService shoppingCartService;
    @Resource//用户
    private UserService userService;
    @Resource//地址
    private AddressBookService addressBookService;
    @Resource // 订单明细
    private OrderDetailService orderDetailService;
    @Override
    @Transactional
    public void submit(Orders orders) {
        //获取登录的是哪个id
        Long currentId = BaseContext.getCurrentId();
        //查询购物车有哪些菜品
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper();
        //条件为当前登录的id
        queryWrapper.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        if (list.size()==0){
            throw new CustomException("菜品为空!");
        }
        //查询用户表
        User user = userService.getById(currentId);
        //查询地址表
        AddressBook address = addressBookService.getById(orders.getAddressBookId());
        if (address==null){
            throw new CustomException("地址为空!");
        }
        //向订单表添加一条数据
        //设置用户id
        orders.setUserId(currentId);
        //设置下单的时间
        orders.setOrderTime(LocalDateTime.now());
        //设置支付的时间
        orders.setCheckoutTime(LocalDateTime.now());
        //设置收货人
        orders.setConsignee(address.getConsignee());
        BigDecimal sum= new BigDecimal(0);
        for (ShoppingCart cart : list) {
           BigDecimal amount = new BigDecimal(cart.getNumber());
           cart.setAmount(amount.multiply(cart.getAmount()));
            sum = sum.add(cart.getAmount());
        }
        //设置金额
        orders.setAmount(sum);
        //设置电话
        orders.setPhone(user.getPhone());
        //待派送
        orders.setStatus(2);
        //设置地址
        orders.setAddress((address.getProvinceName()==null ?"":address.getProvinceName())+
                (address.getCityName()==null ? "":address.getCityName())+
                (address.getDistrictName()==null?"":address.getDistrictName())+
                (address.getDetail()==null?"":address.getDetail()));
        //设置下单用户的名称
        orders.setUserName(address.getConsignee());
        //生成订单id
        long id = IdWorker.getId();
        //下单
        orders.setNumber(String.valueOf(id));
        int insert = mapper.insert(orders);
        if (insert!=1) throw new CustomException("下单失败");
        //将菜品添加到订单明细表
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail,"id");
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }

        orderDetailService.saveBatch(orderDetails);;

        //删除购物车中的数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper1 = new LambdaQueryWrapper();
        queryWrapper1.eq(ShoppingCart::getUserId,currentId);
        boolean remove = shoppingCartService.remove(queryWrapper1);
            if (!remove){
                throw new CustomException("购物车清空事变");
            }

    }

    @Override
    @Transactional
    public IPage page(Integer page, Integer pageSize) {
        //创建分页
        Page<Orders> page1 = new Page(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper11 = new LambdaQueryWrapper();
        queryWrapper11.eq(Orders::getUserId,BaseContext.getCurrentId());
        //查询订单表
        Page<Orders> ordersPage = mapper.selectPage(page1, queryWrapper11);
        //用户表
        User user = userService.getById(BaseContext.getCurrentId());
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        List<OrdersDto> list = new ArrayList<>();
        for (Orders record : page1.getRecords()) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(record,ordersDto);
            ordersDto.setUserName(user.getName());
            ordersDto.setPhone(user.getPhone());
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(OrderDetail::getOrderId,record.getId());
            List<OrderDetail> list1 = orderDetailService.list(queryWrapper);
            ordersDto.setOrderDetails(list1);
            list.add(ordersDto);
        }
        Page<OrdersDto> ordersDtoPage1 = ordersDtoPage.setRecords(list);
        return ordersDtoPage1;
    }
}
